﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enter.DataProxy.DbConnector;

namespace Enter.DataProxy.Statistics
{
	public class PvIpManager : BaseManager
	{

		/// <summary>
		/// 添加用户IpPV
		/// </summary>
		/// <param name="userid"></param>
		/// <param name="ip"></param>
		public void Inserto_User_PvIp(int userid, string ip)
		{
			string time = DateTime.Now.ToShortDateString();

			string sqltxt = @"declare @id int;
							set @id=0;
							select @id=COUNT(1) from userIP 
							where userid=@userid and @ip=ip and adddate=@time;

							if @id=0
							begin
								insert into userIP (userid,ip) values(@userid,@ip);
							end
							set @id=0;
							select @id=id from userpvs 
							where userid=@userid and adddate=@time;
							select @id;
							if @id=0
							begin
								insert into userpvs (userid,pv) values (@userid,1);
							end
							else
							begin
								update userpvs set pv=pv+1 where ID=@id;
							end";

			var db = base.CreateDbWriter();
			ParameterCollection parameters = db.CreateParamCollection(2);
			parameters.Append("userid", userid);
			parameters.Append("ip", ip);
			parameters.Append("time", time);

			
			db.ExecuteNonQuery(sqltxt, parameters);

		}

		/// <summary>
		/// 每十分钟更新一次用户ID PV IP 
		/// </summary>
		public void Update_userStatistics_PvIp(int userid)
		{
			var db = base.CreateDbWriter();
			string time = DateTime.Now.ToShortDateString();
			string sqltxt = @"declare @id int;
							declare @losttime datetime;
							declare @ipcount int;
							declare @pvcount int;
							declare @gettime datetime;
							set @id=0;
							select @id=id,@losttime=losttime from [userStatistics] where userid=@userid;

							set @gettime=getdate();

							select @ipcount=COUNT(1) from userIP where userid=@userid and addtime>@losttime;
							select @pvcount=pv from userpvs where userid=@userid and adddate=@time;
	
							if (@id>0)
							begin

								update [userStatistics] set daypv=@pvcount,dayip=dayip+@ipcount,losttime=@gettime
								where id=@id;

							end
							else
							begin
								insert into [userStatistics] (userid,Yesterdaytime,daypv,dayip,losttime) 
								values (@userid,getdate(),ISNULL(@pvcount,0),ISNULL(@ipcount,0),@gettime);
							end";
			ParameterCollection parameters = db.CreateParamCollection(2);
			parameters.Append("userid", userid);
			parameters.Append("time", time);


			db.ExecuteNonQuery(sqltxt, parameters);
		}
	}
}
